<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ProductService
 *
 * @author QuocDieu
 */
class ProductService {
    
    //get all events
    public static function getAllEvents($proId = 0){
        
        if($proId != 0){
            $criteria = new CDbCriteria();
            $criteria->select = "id, name";
            $criteria->order = "weight";

            $listEvent =  CHtml::listData(Event::model()->findAllByPk($proId, array('order' => 'weight')) , 'id', 'name');
        }
        else
            $listEvent =  CHtml::listData(Event::model()->findAll(array('select'=>'id, name', 'order' => 'weight')), 'id', 'name');            
        
        $listEvent[''] = "=== None ===";
        return $listEvent;
    }

    //get all subbrand
    public function getSubBrand(){
        return CHtml::listData();
    }

    public static function getDropDownListEvents($eventID, $prodID){
        $events = Event::model()->findAll();

        $select = "prodId={$prodID}&eventId={$eventID}";


        foreach ($events as $key => $value)
            $list .= CHtml::tag(
                        "option",
                        array(
                            'value' => 'prodId='.$prodID.'&eventId='.$value->id,
                            'selected' => ($select == 'prodId='.$prodID.'&eventId='.$value->id)?'selected':'',
                        ),
                        CHtml::encode($value['name']),
                        true
                    );

        $eventList = CHtml::tag(
                        'select',
                        array(
                            'id' => 'eventList',
                            'class' => 'ajaxUpdateEvent',
                        ),
                        $list,
                        true
                    );

        echo $eventList;
    }

    public static function getTermByProductID($productID){
        $product = Product::model()->findByAttributes(array('id' => $productID));
        $term = Subrand::model()->findByAttributes(array('id' => $product->sub_brand_id));
      
        return $term;
    }

    public static function printProductFieldByFieldID($field_group, $spec){
        $prod_field_model = ProductField::model()->findAll('field_group_id = '.$field_group->id);
        $prodField = null;
        foreach ($prod_field_model as $key => $value){
            $prodField .= '<tr>';
            $prodField .= CHtml::tag('td', array(), $value->name, true);
            $prodField .= CHtml::tag('td', array(), CHtml::tag('input', array('type' => 'text', 'style' => 'width:600px', 'id' => 'Specification['.$field_group->name.']['.$value->name.']', 'name' => 'Specification['.$field_group->name.']['.$value->name.']', 'value' => $spec[$field_group->name][$value->name]), '', true), true);
            $prodField .= "</tr>";
        }
        //hidden add new product field
        $prodField .= "<tr>";
        $prodField .= CHtml::tag('td', array('colspan' => 2, 'id' => 'tblcell_productfield_'.$field_group->id), '<div id="pfContent_'.$field_group->id.'"></div>', true);
        $prodField .= "</tr>";
        
        return $prodField;
    }

    public static function isThereHasProductFields($field_group_id){
        $prod_field_model = ProductField::model()->findAll('field_group_id = '.$field_group_id);
        
        return count($prod_field_model);
    }

    public static function getAllSubrand($tid){
        $subModel = SubBrandBase::model()->findAll('term_id=:tid', array(':tid' => $tid));
        
        $list = $subModel->brand;
        foreach ($subModel as $subrand => $value){
            $arr[$value->id] = $value->brand->name;
        }
        return $arr;
    }

    public static function getSerializePrice($model){
        if(is_null($model->discount)){
            echo CHtml::tag('div', array('class' => ''), Utility::numberFormat($model->price));
        } else{
            $model->attributes = unserialize($model->discount);    
            if($model->type == 'define'){
                echo CHtml::tag('div', array(), Utility::numberFormat($model->price));
                echo CHtml::tag('div', array('style' => 'color: darkred'), $model->discount);
            } else {
                echo CHtml::tag('div', array(), Utility::numberFormat($model->price));
                echo CHtml::tag('div', array(), 'Giảm: '.Utility::numberFormat($model->discount) . ' ' . $model->type);
                echo CHtml::tag('div', array('style' => 'color: darkred'), 'Còn: '.Utility::numberFormat($model->real_price));
            }
        }        
    }

    public static function getClientSerializePrice($model){
        $model->attributes = unserialize($model->price); 
        if($model->real_price != $model->price ){
            echo CHtml::tag('span', array('style' => 'text-decoration:line-through'), Utility::numberFormat($model->price), true);
            if($model->type=="define")
                echo CHtml::tag('span', array('style' => 'display:block; padding:10px'), "Mức chiết khấu: ".$model->discount.$model->type, true);
            else
                echo CHtml::tag('span', array('style' => 'color: darkred; font-weight:bold; display:block; padding:10px'), "Chỉ còn ".  Utility::numberFormat($model->real_price), true);
            
        }else{
            echo CHtml::tag('span', array(), Utility::numberFormat($model->price));
            if($model->type != "none" && $model->type!="")
                echo CHtml::tag('span', array('style' => 'font-weight:bold; display:block; padding:10px'), "Mức chiết khấu: ".$model->discount.$model->type, true);
        }
    }
    
    public static function printFieldGroup($fields, $d, $cols){
        foreach ($fields as $key => $value){
            echo CHtml::openTag('tr', array('style'=>'background:gray; color: #fff'));
            echo CHtml::tag('td', array('colspan' => $cols, 'class' => 'filed-group'), $key, true);
            echo CHtml::closeTag('tr');    
            
            ProductService::printProductField($key, $value, $d);
        }
    }
    
    public static function printProductField($field, $prodField, $d){
        foreach ($prodField as $key => $value){
            echo CHtml::openTag('tr');
            echo CHtml::tag('td', array('class' => 'product-field'), $key, true);
           //value of products listed in columns
            ProductService::printProductSpecificationByProductField($field, $key, $d[0]);
            ProductService::printProductSpecificationByProductField($field, $key, $d[1]);
            if(count($d)==3)
                ProductService::printProductSpecificationByProductField($field, $key, $d[2]);
            echo CHtml::closeTag('tr');
        }        
    }
    
    public static function printProductSpecificationByProductField($field, $spec, $d){
        $arr = $d[$field];
        echo CHtml::tag('td', array('class' => 'spec'), $arr[$spec], true);        
    }
    
    public static function printProductsCompare($arrID){
        if(!isset($arrID))
            $arrID = ProductService::cookieCompareProduct('compare-list');
        
        $cols = count($arrID)+1;

        $a_ = Product::model()->findByPk($arrID[0]);
        $b_ = Product::model()->findByPk($arrID[1]);

        $a = unserialize($a_->spec->value);
        $b = unserialize($b_->spec->value);

        $d_ = array($a_, $b_);
        $d = array($a, $b);

        if(count($arrID) ==3){
            $c_ = Product::model()->findByPk($arrID[2]);
            $c = unserialize($c_->spec->value);

            $d_ = array($a_, $b_, $c_);
            $d = array($a, $b, $c);            
        }

        ProductService::printFieldGroup($d[ProductService::printLongestSpecification($d_)], $d, $cols);        
    }
    
    public static function cookieCompareProduct($cookieName){
        $cookie = Yii::app()->request->cookies[$cookieName]->value;
        return split(',', $cookie);
    }

    public static function checkCompareProducts($products){
        if($products){
            $arr_term = array();
            $dem = 0;
            foreach($products as $product){
                $prod = Product::model()->findByPk($product);
                $arr_term[] = $prod->subrand->term_id;
            }
            $terms = Term::buildTree();
            foreach($terms as $term){
//                $term['value']->id."<br/>";
                if(in_array($term['value']->id, $arr_term)) {
                    $dem++;
                }
            }
            if($dem > 1)
                return false;
            return true;
        }
        return false;
    }
    
    //return the index of the array which product have full specification.
    public function printLongestSpecification($arr){       
        $longestIndex = 0;
        $index = 0; $maxLength = 0;
        for($i=0, $n=count($arr); $i<$n; $i++){            
            $indexLength = strlen($arr[$i]->spec->value);
            if($indexLength > $maxLength){                
                $index = $i;
                $maxLength = $indexLength;
            }
        }
        return $index;
    }
    
    public static function getProductImage($id){        
        $prod = Product::model()->findByPk($id);               
        echo CHtml::tag('td', array(), CHtml::image(Yii::app()->baseUrl."/".$prod->uri, $prod->alias, array()), true);
    }

    public static function getProductName($id){
        $prod = Product::model()->findByPk($id);
        echo CHtml::tag('th', array(), CHtml::link($prod->name, array('product/view', "id" => $prod->id, "alias" => $prod->alias), array()), true);
    }
    
    public static function getRefenceProduct($sub_brand_id, $prodID=null){        
        return $productModel = Product::model()->findAll('sub_brand_id = '.$sub_brand_id. ' AND id !='.$prodID.' limit 10');
    }

    public static function getPromotionProducts($term_id){
        $data = Product::model()->with(array(
            'subrand' => array(
                'condition' => "term_id = ".$term_id,
            ),
        ))->findAll(array(
            'select' => "id, name, alias, price, discount, uri",
            'condition' => "status = 1 and discount is not NULL",
        ));
        return $data;
    }

    public static function getNameAndEmail($id){
        $info = Comment::model()->findByPk($id);
        $model = new Comment('search');
        $model->unsetAttributes();  // clear any default values
        $model->attributes = unserialize($info->account);
        return $model->name." --- ".$model->email;
    }
}
?>
